<?php

/**
 * @property Session $session
 * @property Input $input
 * @property Loader $loader
 * @property Cookie $cookie
 * @property array $uriArray
 */

class App {

    /**
     *
     * @var Uri 
     */
    var $uri = null;

    /**
     *
     * @var Session 
     */
    var $session = null;
    
    /**
     *
     * @var Input 
     */
    var $input = null;
    
    /**
     *
     * @var Cookie 
     */
    var $cookie = null;
    
    /**
     *
     * @var Loader 
     */
    var $loader = null;

    public function __construct() {
        $this->session = Session::getInstance();
        $this->input = Input::getInstance();
        $this->cookie = Cookie::getInstance();
        $this->loader = new Loader();
    }

    public function setUri(Uri $uri){
        $this->uri = $uri;
    }
    

    function loadController($class, $action = false) {


        $classPathArray = preg_split('[\\/]', $class, -1, PREG_SPLIT_NO_EMPTY);

        $classPath = "";
        $className = "";

        //rebuild the class path with proper case and extract the class name
        for ($i = 0; $i < count($classPathArray); $i++) {
            if ($i != count($classPathArray) - 1) {
                $classPath .= strtolower($classPathArray[$i]) . '/';
            } else {
                $className = ucfirst(strtolower($classPathArray[$i])) . "Controller";
                $classPath .= $className;
            }
        }


        $file = BASE_PATH . "/app/controller/" . $classPath . ".php";


        if (!file_exists($file)) {
            throw new HttpCodeException(HttpCodeException::PAGE_NOT_FOUND);
        } 
        require_once ($file);

        $controller = new $className();
        /* @var $controller Controller */
        
        $controller->setUri($this->uri);
        
        //$class->setUriArray($uri_array);
        if (!$action) {
            $action = 'index';
        }

        $firstchar = substr($action, 0, 1);

        if (method_exists($controller, $action)) {
            if ($firstchar == "_") {
                throw new HttpCodeException(HttpCodeException::PAGE_NOT_FOUND);
            }
            $controller->{$action}();
        } else {
            throw new HttpCodeException(HttpCodeException::PAGE_NOT_FOUND);
        }
    }

    function loadLibrary($library) {
        $library = ucfirst(strtolower($library));
        $file = BASE_PATH . "/app/lib/" . $library . ".php";

        if (!file_exists($file)){
            throw new LoaderException('Unable to load library: ' . $library);
        }
        require_once($file);
    }

}
